<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614>　
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\Config;
use think\Session;
use think\Db;

class Auth
{

    /**
     * 权限验证
     * @param string $url 验证链接url
     * @param int    $uid 验证uid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function check( $url='', $uid=0 )
    {
        $url = strtolower( trim( $url ) );
        $uid = intval( $uid );
        if( !$url || !$uid ) {
            return false;
        }

        //获取用户权限组id
        $groupIdArr = db( 'auth_role_member' )->where( ['uid'=>$uid] )->column( 'role_id' );
        if( !$groupIdArr ) {
            return false;
        }

        //获取用户标识
        $userAuth = session( 'admin.user_auth' );
        //$identity = $userAuth['identity'];

        //获取用户组的权限
        $where             = [];
        $where['id']       = ['in', $groupIdArr];
        //$where['identity'] = $identity;
        $where['status']   = 1;//启用
        $rulesRet = db( 'auth_role' )->where( ['id'=>['in', $groupIdArr]] )->column( 'rules' );
        $ruleArr  = $rulesRet ? array_unique( explode( ',', implode( ',', $rulesRet ) ) ) : [];
        if( !$ruleArr ) {
            return false;
        }

        //获取菜单权限
        $where       = [];
        $where['id'] = ['in', $ruleArr];
        $field   = 'module, url';
        $menuRet = db( 'menu' )->field( $field )->where( $where )->select();
        $urlArr  = [];
        if( $menuRet ) {
            foreach ( $menuRet as $key => $val ) {
                $urlArr[] = strtolower( $val['module'].'/'.$val['url'] );
            }
        }

        if( in_array( $url, $urlArr ) ) {
            return true;
        }
        return false;
    }
    
}